package com.pinyougou.sellergoods.server.implement;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.pinyougou.group.Goods;
import com.pinyougou.mapper.*;
import com.pinyougou.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pinyougou.pojo.TbGoodsExample.Criteria;
import com.pinyougou.sellergoods.service.GoodsService;

import com.pinyougou.utils.PageResult;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

/**
 * 服务实现层
 * @author Administrator
 *
 */
@Service
@Transactional//添加事务
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private TbGoodsMapper goodsMapper;
	@Autowired
	private TbGoodsDescMapper goodsDescMapper;
	@Autowired
	private TbBrandMapper brandMapper;
	@Autowired
	private TbSellerMapper sellerMapper;
	@Autowired
	private TbItemMapper itemMapper;
	
	/**
	 * 查询全部
	 */
	@Override
	public List<TbGoods> findAll() {
		return goodsMapper.selectByExample(null);
	}

	/**
	 * 按分页查询
	 */
	@Override
	public PageResult findPage(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);		
		Page<TbGoods> page=   (Page<TbGoods>) goodsMapper.selectByExample(null);
		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 增加（同时向tb_goods表、tb_goods_desc表和tb_item表中添加数据）
	 * TbGoodsMapper映射文件中修改insert方法，添加完一个商品后，为其对应的实体类的id赋值
	 */
	@Override
	public void add(Goods goods) {
		//1、添加数据到b_goods表中
		//1.1设置商品审核默认为"0":未审核
		goods.getGoods().setAuditStatus("0");
		//1.2向b_goods表中添加数据
		goodsMapper.insert(goods.getGoods());
		//2、添加数据到tb_goods_desc表中
		//2.1将b_goods表与tb_goods_desc表进行关联
		goods.getGoodsDesc().setGoodsId(goods.getGoods().getId());
		//2.2向tb_goods_desc表中添加数据
		goodsDescMapper.insert(goods.getGoodsDesc());

		//3、添加数据到tb_item表中
		updateTBItem(goods);

	}

	/**
	 * 添加数据到tb_item表中
	 * @param goods
	 */
	private void updateTBItem(Goods goods) {
		//3.1得到itemList
		List<TbItem> itemList = goods.getItems();
		//3.2遍历itemList
		for (TbItem item : itemList) {
			//3.3得到商品名称
			String goodsName = goods.getGoods().getGoodsName();
			//3.4得到选中的规格列表
			Map specMap = JSON.parseObject(item.getSpec());
			for (Object key : specMap.keySet()) {
				//3.5构造并设置标题
				String title = goodsName +" "+ specMap.get(key);
				item.setTitle(title);
				//3.6设置商品id
				item.setGoodsId(goods.getGoods().getId());
				//3.7设置三级分类
				item.setCategoryid(goods.getGoods().getCategory3Id());
				//3.8设置商家编号
				item.setSellerId(goods.getGoods().getSellerId());
				//3.9设置时间属性
				item.setCreateTime(new Date());
				item.setUpdateTime(new Date());
				//3.10设置品牌
				TbBrand brand = brandMapper.selectByPrimaryKey(goods.getGoods().getBrandId());
				item.setBrand(brand.getName());
				//3.11设置店铺名称
				TbSeller seller = sellerMapper.selectByPrimaryKey(goods.getGoods().getSellerId());
				item.setSeller(seller.getNickName());
				//3.12设置图片
				List<Map> images = JSON.parseArray(goods.getGoodsDesc().getItemImages(),Map.class);
				if (images.size() > 0)
					item.setImage(images.get(0).get("url")+"");
			}
			itemMapper.insert(item);
		}
	}


	/**
	 * 修改（同时修改tb_goods表、tb_goods_desc表、tb_item表中的记录）
	 */
	@Override
	public void update(Goods goods){
		//1、修改tb_goods表中的记录
		goodsMapper.updateByPrimaryKey(goods.getGoods());
		//2、修改tb_goods_desc表中的记录
		goodsDescMapper.updateByPrimaryKey(goods.getGoodsDesc());
		//3、修改tb_item表中的记录
		//3.1首先删除原有的记录
		TbItemExample example = new TbItemExample();
		example.createCriteria().andGoodsIdEqualTo(goods.getGoods().getId());
		itemMapper.deleteByExample(example);
		//3.2然后向表中添加新的记录
		updateTBItem(goods);
	}	
	
	/**
	 * 根据ID获取实体(组合类对象)
	 * @param id
	 * @return
	 */
	@Override
	public Goods findOne(Long id){
		//1.根据商品id查询出商品对象
		TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
		//2.根据商品id查询出商品描述对象
		TbGoodsDesc tbGoodsDesc = goodsDescMapper.selectByPrimaryKey(id);
		//3.根据商品id查询与此商品相关的规格列表
		TbItemExample example = new TbItemExample();
		example.createCriteria().andGoodsIdEqualTo(id);
		List<TbItem> tbItems = itemMapper.selectByExample(example);
		//4.构造返回的对象
		Goods goods = new Goods();
		goods.setGoods(tbGoods);
		goods.setGoodsDesc(tbGoodsDesc);
		goods.setItems(tbItems);
		return goods;
	}

	/**
	 * 批量删除
	 */
	@Override
	public void delete(Long[] ids) {
		for(Long id:ids){
			goodsMapper.deleteByPrimaryKey(id);
		}		
	}

	/**
	 * 条件查询+分页
	 * @param goods
	 * @param pageNum 当前页 码
	 * @param pageSize 每页记录数
	 * @return
	 */
	@Override
	public PageResult findPage(TbGoods goods, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		
		TbGoodsExample example=new TbGoodsExample();
		Criteria criteria = example.createCriteria();
		
		if(goods!=null){			
			if(goods.getSellerId()!=null && goods.getSellerId().length()>0){
				criteria.andSellerIdEqualTo(goods.getSellerId());
			}
			if(goods.getGoodsName()!=null && goods.getGoodsName().length()>0){
				criteria.andGoodsNameLike("%"+goods.getGoodsName()+"%");
			}
			if(goods.getAuditStatus()!=null && goods.getAuditStatus().length()>0){
				criteria.andAuditStatusEqualTo(goods.getAuditStatus());
			}
			if(goods.getIsMarketable()!=null && goods.getIsMarketable().length()>0){
				criteria.andIsMarketableLike("%"+goods.getIsMarketable()+"%");
			}
			if(goods.getCaption()!=null && goods.getCaption().length()>0){
				criteria.andCaptionLike("%"+goods.getCaption()+"%");
			}
			if(goods.getSmallPic()!=null && goods.getSmallPic().length()>0){
				criteria.andSmallPicLike("%"+goods.getSmallPic()+"%");
			}
			if(goods.getIsEnableSpec()!=null && goods.getIsEnableSpec().length()>0){
				criteria.andIsEnableSpecLike("%"+goods.getIsEnableSpec()+"%");
			}
			if(goods.getIsDelete()!=null && goods.getIsDelete().length()>0){
				criteria.andIsDeleteEqualTo(goods.getIsDelete());
			}
	
		}
		
		Page<TbGoods> page= (Page<TbGoods>)goodsMapper.selectByExample(example);		
		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 审核商品
	 * @param ids
	 * @param status
	 */
	@Override
	public void updateStatus(long[] ids, String status) {
		for (long id : ids) {
			//根据商品id查询商品对象
			TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
			//修改商品状态
			tbGoods.setAuditStatus(status);
			//修改商品记录
			goodsMapper.updateByPrimaryKey(tbGoods);
		}
	}

}
